import config from './index'
import tool from './tool.js'
const STATUS = {
	LOGIN: 401
}
class request {
	constructor(arg) {
		this.state = {
			BASE_URL: config.BASE_URL,
			data: {},
			MTHODS: "GET"
		}
	}
	get(url, param) {
		this.state.MTHODS = "GET"
		return this.request(url, param)
	}
	post(url, param) {
		this.state.MTHODS = "POST"
		return this.request(url, param)
	}
	request(url, param) {
		uni.showLoading({
			title:'正在加载中',
			mask:true,
		})
		const {
			BASE_URL,
			data,
			MTHODS
		} = this.state
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + url,
				method: MTHODS,
				header: {
					// Authorization:uni.getStorageSync('Authorization'),
					Authorization: `Bearer ${uni.getStorageSync('Authorization')}`
				},
				data: {
					...data,
					...param,
					id: (param && param.id) || (data && data.id) || uni.getStorageSync('uid'),
					uid: uni.getStorageSync('uid')
				},
				success: res => {
					uni.hideLoading()
					console.log(res, "res:", url)
					const {
						code,
						data
					} = res
					const {
						message,
						pageTo
					} = tool
					if (data.status === false) {
						message(data.msg)
					}
					if (data.status === STATUS.LOGIN) {
						message('请先登录').then(() => {
							pageTo('/pages/login/login')
						})
					}
					resolve(data)
				},
				fail:err=> {
					console.error(err,"报错内容")
				},complete: (a,b,c) => {
					console.log(a,b,c,"complete")
				}
			})
		})
	}

}
export default new request()
